import axios from "axios";
// import { createApp } from "vue";
// import { ElMessage, ElLoading } from "element-plus";
import router from "@/router";
import qs from "qs";

axios.defaults.baseURL = "";
//let vue = createApp();
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API,
  timeout: 10000,
});

//配置请求拦截
let LoadingStance = null;
service.interceptors.request.use(
  (config) => {
    // console.log('网络请求：',config);
    LoadingStance = ElLoading.service({ fullscreen: true });
    // if (localStorage.getItem('token')) {
    //   axios.defaults.headers.authorization = localStorage.getItem('token')
    // }
    //axios.defaults.headers.authorization =
    // window.sessionStorage.getItem('token')
    config.headers.authorization = window.sessionStorage.getItem("token");
    //console.log(config)
    return config;
  },
  (error) => {
    //请求出错了(还没有发出去)
    return Promise.reject(error);
  }
);

//配置响应拦截
service.interceptors.response.use(
  (response) => {
    // console.log("数据返回：", response);
    LoadingStance.close();
    const res = response.data;
    if (Number(response.status) === 401) {
      // if (localStorage.getItem('token')) {
      router.push("/login");
      return;
      // }
    }
    // if (parseInt(res.code) !== 200) {
    //   ElMessage({
    //     message: res.msg || 'Error',
    //     type: 'error',
    //     duration: 3000,
    //   })
    // }
    return res;
  },
  (error) => {
    // console.log('err' + error); // for debug
    ElMessage({
      message: "请求失败请稍后重试！",
      type: "error",
      duration: 3000,
    });
    LoadingStance.close();
    return Promise.reject(error);
    // const obj = {
    //   code: '9999',
    //   msg: '错误'
    // }
    // return obj
  }
);

/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function get(url, params) {
  // console.log('GET请求参数：',params);
  return new Promise((resolve, reject) => {
    service
      .get(url, {
        params: params,
      })
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        reject(err.data);
      });
  });
}

/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function post(url, params) {
  return new Promise((resolve, reject) => {
    service
      .post(url, qs.stringify(params))
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        reject(err.data);
      });
  });
}

//vue.config.globalProperties.$http = service
export default {
  install: (app) => {
      app.config.globalProperties['$http'] = service;
  }
}